package com.itheima.health.job.task;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
@Slf4j
public class CleanTask {
    private final static Long MAX_TIME = 30*1000L;//最大允许存放时间

    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private SetmealService setmealService;
    @Autowired
    private QiniuUtils qiniuUtils;

    @Scheduled(cron = "0/5 * * * * ?")
    public void cheanImg() {
        log.info("[定时-执行删除]");
        Set<String> members = redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).members();
        for (String fileName : members) {
            //判断图片创建时间
            String[] split = fileName.split("_");
            Long createTime = Long.valueOf(split[0]);
            if ((System.currentTimeMillis() - createTime) < MAX_TIME) {
                log.info("[定时-未超时]fileName: {}",fileName);
                continue;
            }
            //判断图片使用次数
            Integer count = setmealService.countByImg(fileName);
            if (count == 0) {
                qiniuUtils.deleteFileFromQiniu(fileName);
                log.info("[定时-七牛云超时删除]fileName: {}",fileName);
            }
            //从redis删除
            redisTemplate.boundSetOps(RedisConst.SETMEAL_PIC_RESOURCES).remove(fileName);
            log.info("[定时-redis超时删除]fileName: {}",fileName);
        }
    }
}
